package com.weilan.ark3.read;
//import com.example.enerark_ems.rtuSlave.SerialPortSlave;

import com.weilan.ark3.buffer.DataArray;
import com.weilan.ark3.buffer.MsgQueue;
import com.weilan.ark3.buffer.OverallSituation;
import com.weilan.ark3.common.GlobalParam;
import com.weilan.ark3.entity.ControlDto;
import com.weilan.ark3.entity.ControlRtu;
import com.weilan.ark3.serial.SerialPortCom3Service;
import com.weilan.ark3.service.ControlRtuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 *
 */
@Component
@Slf4j
public class COM3ReadData  {

    @Autowired
    private SerialPortCom3Service serialPortCom3Service;

    public void ReadCom3Data() {
        while (true) {
            if (MsgQueue.controlQueuePVSize() > 0) {
                ControlDto controlDto = MsgQueue.readFromPVQueue();
                serialPortCom3Service.writeRegister(controlDto);
            }
            if (MsgQueue.com3QueueSize() > 0) {
                ControlRtu controlRtu = MsgQueue.readFromCom3Queue();
                //起始地址
                Integer address = controlRtu.getAddress();
                //长度
                Integer len = controlRtu.getLen();
                Integer slaveId = controlRtu.getSlaveId();
                try {
                    //日志记录发送的报文信息
//                  tcpServer.info("读取数据的报文:" + "ID:" + controlRtu.getSlaveId() + " " + "address:" + controlRtu.getAddress() + " " + "len:" + controlRtu.getLen());
                    short[] rtuData = serialPortCom3Service.readRtuData(controlRtu.getSlaveId(), controlRtu.getAddress(), controlRtu.getLen());
                    if (rtuData != null && rtuData.length == len) {
                        //将读取的数据转换为字符串
                        String rtuString = Arrays.toString(rtuData);
                        System.arraycopy(rtuData, 0, DataArray.slaveDataMap.get(slaveId), address, len);
                        //System.out.println("每次更新的数组" + Arrays.toString(DataArray.data));
                        String key = controlRtu.getModuleName() + ":" + controlRtu.getDeviceId() + ":" + controlRtu.getInstructName();
                        //将字符串做截取
                        String data = rtuString.substring(1, rtuString.length() - 1);
                        OverallSituation.CacheData.put(key, data);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
